const express = require('express');
const {
  login,
  getCurrentAdmin,
  getParkingLots,
  getParkingLotById,
  createParkingLot,
  updateParkingLot,
  deleteParkingLot,
  getParkingLotReviews,
  addParkingLotReview,
  updateReviewStatus,
  replyToReview,
  getParkingLotCategories,
  searchUsers,
  getParkingLotManagers,
  addParkingLotManager,
  removeParkingLotManager,
  updateParkingLotManagerEmail,
  getAdmins,
  createAdmin,
  updateAdmin,
  deleteAdmin,
  getOrders,
  getOrderById,
  getUsersList,
  createCategory,
  updateCategory,
  deleteCategory,
  getSystemConfig,
  updateSystemConfig,
  testSms,
  testEmail,
  getCouponTemplates,
  createCouponTemplate,
  updateCouponTemplate,
  deleteCouponTemplate,
  getDashboardStats,
  issueCouponToUser
} = require('../controllers/adminController');
const {
  getParkingLotPricing,
  updateParkingLotPricing,
  setDefaultPricing,
  getAllParkingLotsPricing,
  previewPriceCalculation
} = require('../controllers/pricingController');
const { manualCheckOrders } = require('../services/orderScheduler');
const { uploadImage, deleteImage } = require('../controllers/uploadController');
const { authenticateToken } = require('../middleware/auth');

const router = express.Router();

/**
 * @route   POST /api/admin/login
 * @desc    管理员登录
 * @access  Public
 * @body    { username: string, password: string }
 * @returns { success: boolean, message: string, data: { token: string, userInfo: object } }
 */
router.post('/login', login);

/**
 * @route   GET /api/admin/profile
 * @desc    获取当前登录管理员信息
 * @access  Private (需要JWT认证)
 * @returns { success: boolean, data: object }
 */
router.get('/profile', authenticateToken, getCurrentAdmin);

// ==================== 停车场管理路由 ====================

/**
 * @route   GET /api/admin/parking-lots
 * @desc    获取停车场列表（支持分页和搜索）
 * @access  Private (需要JWT认证)
 * @query   { page?: number, pageSize?: number, name?: string, status?: string }
 * @returns { success: boolean, data: { list: array, total: number, page: number, pageSize: number, totalPages: number } }
 */
router.get('/parking-lots', authenticateToken, getParkingLots);

/**
 * @route   GET /api/admin/parking-lots/:id
 * @desc    获取单个停车场详细信息
 * @access  Private (需要JWT认证)
 * @returns { success: boolean, data: object }
 */
router.get('/parking-lots/:id', authenticateToken, getParkingLotById);

/**
 * @route   POST /api/admin/parking-lots
 * @desc    创建新停车场
 * @access  Private (需要JWT认证)
 * @body    { name: string, category_id?: number, address: string, latitude: number, longitude: number, ... }
 * @returns { success: boolean, message: string, data: object }
 */
router.post('/parking-lots', authenticateToken, createParkingLot);

/**
 * @route   PUT /api/admin/parking-lots/:id
 * @desc    更新停车场信息
 * @access  Private (需要JWT认证)
 * @body    { name?: string, category_id?: number, address?: string, ... }
 * @returns { success: boolean, message: string }
 */
router.put('/parking-lots/:id', authenticateToken, updateParkingLot);

/**
 * @route   DELETE /api/admin/parking-lots/:id
 * @desc    删除停车场
 * @access  Private (需要JWT认证)
 * @returns { success: boolean, message: string }
 */
router.delete('/parking-lots/:id', authenticateToken, deleteParkingLot);

// ==================== 停车场评价管理路由 ====================

/**
 * @route   GET /api/admin/parking-lots/:parking_lot_id/reviews
 * @desc    获取指定停车场的评价列表
 * @access  Private (需要JWT认证)
 * @query   { page?: number, pageSize?: number, status?: string }
 * @returns { success: boolean, data: { list: array, total: number, page: number, pageSize: number, totalPages: number } }
 */
router.get('/parking-lots/:parking_lot_id/reviews', authenticateToken, getParkingLotReviews);

/**
 * @route   POST /api/admin/parking-lots/reviews
 * @desc    管理员手动添加停车场评论
 * @access  Private (需要JWT认证)
 * @body    { parking_lot_id: number, user_nickname: string, user_avatar?: string, rating: number, comment: string, created_at?: string, status?: string }
 * @returns { success: boolean, message: string, data: object }
 */
router.post('/parking-lots/reviews', authenticateToken, addParkingLotReview);

/**
 * @route   PUT /api/admin/reviews/:id/status
 * @desc    更新评价状态（显示/隐藏）
 * @access  Private (需要JWT认证)
 * @body    { status: 'visible' | 'hidden' }
 * @returns { success: boolean, message: string }
 */
router.put('/reviews/:id/status', authenticateToken, updateReviewStatus);

/**
 * @route   POST /api/admin/reviews/:id/reply
 * @desc    回复评价
 * @access  Private (需要JWT认证)
 * @body    { content: string }
 * @returns { success: boolean, message: string, data: { id: number } }
 */
router.post('/reviews/:id/reply', authenticateToken, replyToReview);

// ==================== 停车场价格配置管理路由 ====================

/**
 * @route   GET /api/admin/parking-lots/pricing
 * @desc    获取所有停车场的价格配置概览
 * @access  Private (需要JWT认证)
 * @query   { page?: number, limit?: number, status?: string }
 * @returns { success: boolean, data: { list: array, total: number, page: number, limit: number, totalPages: number } }
 */
router.get('/parking-lots/pricing', authenticateToken, getAllParkingLotsPricing);

/**
 * @route   GET /api/admin/parking-lots/:id/pricing
 * @desc    获取指定停车场的价格配置
 * @access  Private (需要JWT认证)
 * @returns { success: boolean, data: { parking_lot_id: number, parking_lot_name: string, price_rules: object } }
 */
router.get('/parking-lots/:id/pricing', authenticateToken, getParkingLotPricing);

/**
 * @route   PUT /api/admin/parking-lots/:id/pricing
 * @desc    更新指定停车场的价格配置
 * @access  Private (需要JWT认证)
 * @body    { price_rules: { daily_prices: object, daily_price_after_7: number, description?: string } }
 * @returns { success: boolean, message: string, data: object }
 */
router.put('/parking-lots/:id/pricing', authenticateToken, updateParkingLotPricing);

/**
 * @route   POST /api/admin/parking-lots/pricing/default
 * @desc    批量设置停车场的默认价格配置
 * @access  Private (需要JWT认证)
 * @body    { parking_lot_ids: array, default_config?: object }
 * @returns { success: boolean, message: string, data: { affected_count: number, default_config: object } }
 */
router.post('/parking-lots/pricing/default', authenticateToken, setDefaultPricing);

/**
 * @route   GET /api/admin/pricing/preview
 * @desc    预览价格计算结果
 * @access  Private (需要JWT认证)
 * @query   { parking_lot_id: number, entry_time: string, exit_time: string }
 * @returns { success: boolean, data: object }
 */
router.get('/pricing/preview', authenticateToken, previewPriceCalculation);

// ==================== 停车场分类路由 ====================

/**
 * @route   GET /api/admin/parking-lot-categories
 * @desc    获取停车场分类列表
 * @access  Private (需要JWT认证)
 * @returns { success: boolean, data: array }
 */
router.get('/parking-lot-categories', authenticateToken, getParkingLotCategories);

// ==================== 停车场分类管理路由 ====================

/**
 * @route   POST /api/admin/categories
 * @desc    创建新的停车场分类
 * @access  Private (需要JWT认证)
 * @body    { name: string, icon_url?: string, sort_order?: number }
 * @returns { success: boolean, message: string, data: object }
 */
router.post('/categories', authenticateToken, createCategory);

/**
 * @route   PUT /api/admin/categories/:id
 * @desc    更新停车场分类
 * @access  Private (需要JWT认证)
 * @body    { name?: string, icon_url?: string, sort_order?: number }
 * @returns { success: boolean, message: string }
 */
router.put('/categories/:id', authenticateToken, updateCategory);

/**
 * @route   DELETE /api/admin/categories/:id
 * @desc    删除停车场分类
 * @access  Private (需要JWT认证)
 * @returns { success: boolean, message: string }
 */
router.delete('/categories/:id', authenticateToken, deleteCategory);

// ==================== 用户搜索路由 ====================

/**
 * @route   GET /api/admin/users/search
 * @desc    搜索用户（用于指派员工）
 * @access  Private (需要JWT认证)
 * @query   { keyword: string }
 * @returns { success: boolean, data: array }
 */
router.get('/users/search', authenticateToken, searchUsers);

// ==================== 停车场员工管理路由 ====================

/**
 * @route   GET /api/admin/parking-lots/:parkingLotId/managers
 * @desc    获取指定停车场的所有管理员
 * @access  Private (需要JWT认证)
 * @returns { success: boolean, data: array }
 */
router.get('/parking-lots/:parkingLotId/managers', authenticateToken, getParkingLotManagers);

/**
 * @route   POST /api/admin/parking-lots/:parkingLotId/managers
 * @desc    为指定停车场添加管理员
 * @access  Private (需要JWT认证)
 * @body    { userId: number }
 * @returns { success: boolean, message: string, data: object }
 */
router.post('/parking-lots/:parkingLotId/managers', authenticateToken, addParkingLotManager);

/**
 * @route   DELETE /api/admin/parking-lots/:parkingLotId/managers/:userId
 * @desc    移除指定停车场的管理员
 * @access  Private (需要JWT认证)
 * @returns { success: boolean, message: string }
 */
router.delete('/parking-lots/:parkingLotId/managers/:userId', authenticateToken, removeParkingLotManager);

/**
 * @route   PUT /api/admin/parking-lots/:parkingLotId/managers/:userId/email
 * @desc    更新停车场管理员邮箱
 * @access  Private (需要JWT认证)
 * @body    { email: string }
 * @returns { success: boolean, message: string, data: object }
 */
router.put('/parking-lots/:parkingLotId/managers/:userId/email', authenticateToken, updateParkingLotManagerEmail);

// ==================== 后台管理员管理路由 ====================

/**
 * @route   GET /api/admin/admins
 * @desc    获取管理员列表
 * @access  Private (需要JWT认证)
 * @query   { page?: number, pageSize?: number, username?: string }
 * @returns { success: boolean, data: { list: array, total: number, page: number, pageSize: number, totalPages: number } }
 */
router.get('/admins', authenticateToken, getAdmins);

/**
 * @route   POST /api/admin/admins
 * @desc    创建新管理员
 * @access  Private (需要JWT认证)
 * @body    { username: string, password: string, is_super_admin?: boolean, is_active?: boolean }
 * @returns { success: boolean, message: string, data: object }
 */
router.post('/admins', authenticateToken, createAdmin);

/**
 * @route   PUT /api/admin/admins/:id
 * @desc    更新管理员信息
 * @access  Private (需要JWT认证)
 * @body    { username?: string, password?: string, is_super_admin?: boolean, is_active?: boolean }
 * @returns { success: boolean, message: string }
 */
router.put('/admins/:id', authenticateToken, updateAdmin);

/**
 * @route   DELETE /api/admin/admins/:id
 * @desc    删除管理员
 * @access  Private (需要JWT认证)
 * @returns { success: boolean, message: string }
 */
router.delete('/admins/:id', authenticateToken, deleteAdmin);

// ==================== 用户管理路由 ====================

/**
 * @route   GET /api/admin/users
 * @desc    获取用户列表（支持分页和搜索）
 * @access  Private (需要JWT认证)
 * @query   { page?: number, pageSize?: number, nickname?: string, phone_number?: string }
 * @returns { success: boolean, data: { list: array, total: number, page: number, pageSize: number, totalPages: number } }
 */
router.get('/users', authenticateToken, getUsersList);

// ==================== 系统配置管理路由 ====================

/**
 * @route   GET /api/admin/system-config
 * @desc    获取系统配置
 * @access  Private (需要JWT认证)
 * @query   { config_key: string }
 * @returns { success: boolean, data: { config_key: string, config_value: string, description: string } }
 */
router.get('/system-config', authenticateToken, getSystemConfig);

/**
 * @route   POST /api/admin/system-config
 * @desc    更新系统配置
 * @access  Private (需要JWT认证)
 * @body    { config_key: string, config_value: string, description?: string }
 * @returns { success: boolean, message: string }
 */
router.post('/system-config', authenticateToken, updateSystemConfig);

/**
 * @route   POST /api/admin/test-sms
 * @desc    发送测试短信
 * @access  Private (需要JWT认证)
 * @body    { phone: string }
 * @returns { success: boolean, message: string, data?: object }
 */
router.post('/test-sms', authenticateToken, testSms);

/**
 * @route   POST /api/admin/test-email
 * @desc    发送测试邮件
 * @access  Private (需要JWT认证)
 * @body    { email: string }
 * @returns { success: boolean, message: string, data?: object }
 */
router.post('/test-email', authenticateToken, testEmail);

// ==================== 订单管理路由 ====================

/**
 * @route   GET /api/admin/orders
 * @desc    获取订单列表（支持复杂筛选和分页）
 * @access  Private (需要JWT认证)
 * @query   { page?: number, pageSize?: number, order_number?: string, license_plate?: string, status?: string, parking_lot_id?: number, user_id?: number, start_date?: string, end_date?: string }
 * @returns { success: boolean, data: { list: array, total: number, page: number, pageSize: number, totalPages: number } }
 */
router.get('/orders', authenticateToken, getOrders);

/**
 * @route   GET /api/admin/orders/:id
 * @desc    获取单个订单详细信息
 * @access  Private (需要JWT认证)
 * @returns { success: boolean, data: object }
 */
router.get('/orders/:id', authenticateToken, getOrderById);

/**
 * @route   POST /api/admin/orders/check-expired
 * @desc    手动检查并更新超时订单状态
 * @access  Private (需要JWT认证)
 * @returns { success: boolean, data: object }
 */
router.post('/orders/check-expired', authenticateToken, async (req, res) => {
  try {
    const result = await manualCheckOrders();
    res.status(200).json({
      success: true,
      data: result,
      message: '订单状态检查完成'
    });
  } catch (error) {
    console.error('手动检查订单状态失败:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});

// ==================== 优惠券模板管理路由 ====================

/**
 * @route   GET /api/admin/coupon-templates
 * @desc    获取优惠券模板列表（支持分页和搜索）
 * @access  Private (需要JWT认证)
 * @query   { page?: number, pageSize?: number, name?: string }
 * @returns { success: boolean, data: { list: array, total: number, page: number, pageSize: number, totalPages: number } }
 */
router.get('/coupon-templates', authenticateToken, getCouponTemplates);

/**
 * @route   POST /api/admin/coupon-templates
 * @desc    创建优惠券模板
 * @access  Private (需要JWT认证)
 * @body    { name: string, type: string, value: number, min_spend?: number, validity_type: string, valid_days?: number, valid_start_date?: string, valid_end_date?: string, total_quantity?: number, is_active?: boolean }
 * @returns { success: boolean, message: string, data: { id: number } }
 */
router.post('/coupon-templates', authenticateToken, createCouponTemplate);

/**
 * @route   PUT /api/admin/coupon-templates/:id
 * @desc    更新优惠券模板
 * @access  Private (需要JWT认证)
 * @body    { name: string, type: string, value: number, min_spend?: number, validity_type: string, valid_days?: number, valid_start_date?: string, valid_end_date?: string, total_quantity?: number, is_active?: boolean }
 * @returns { success: boolean, message: string }
 */
router.put('/coupon-templates/:id', authenticateToken, updateCouponTemplate);

/**
 * @route   DELETE /api/admin/coupon-templates/:id
 * @desc    删除优惠券模板
 * @access  Private (需要JWT认证)
 * @returns { success: boolean, message: string }
 */
router.delete('/coupon-templates/:id', authenticateToken, deleteCouponTemplate);

// ==================== Dashboard 统计数据路由 ====================

/**
 * @route   GET /api/admin/dashboard/stats
 * @desc    获取Dashboard统计数据
 * @access  Private (需要JWT认证)
 * @returns { success: boolean, data: { todayRevenue: number, totalRevenue: number, todayNewUsers: number, totalUsers: number, pendingOrders: number, totalParkingLots: number } }
 */
router.get('/dashboard/stats', authenticateToken, getDashboardStats);

// ==================== 优惠券发放路由 ====================

/**
 * @route   POST /api/admin/coupons/issue
 * @desc    向用户发放优惠券
 * @access  Private (需要JWT认证)
 * @body    { template_id: number, user_id: number }
 * @returns { success: boolean, message: string, data: { coupon_id: number, user_nickname: string, template_name: string, expiry_date: string } }
 */
router.post('/coupons/issue', authenticateToken, issueCouponToUser);

// ==================== 文件上传路由 ====================

/**
 * @route   POST /api/admin/upload/image
 * @desc    上传图片文件
 * @access  Private (需要JWT认证)
 * @body    FormData with 'file' field
 * @returns { success: boolean, message: string, data: { url: string, filename: string, ... } }
 */
router.post('/upload/image', authenticateToken, uploadImage);

/**
 * @route   DELETE /api/admin/upload/image/:filename
 * @desc    删除图片文件
 * @access  Private (需要JWT认证)
 * @param   filename - 文件名
 * @returns { success: boolean, message: string }
 */
router.delete('/upload/image/:filename', authenticateToken, deleteImage);

module.exports = router;
